package com.gl.basis.zuul.util;

import com.alibaba.fastjson.JSONObject;
import com.gl.basis.zuul.exception.ZuulFilterException;
import com.netflix.zuul.context.RequestContext;
import org.springframework.web.context.request.RequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

/**
 *
 * 工具类
 *
 */
public class ZuulUtil {

    private static final String CROWD_ERROR = "crowd.error";

    private static final String ERROR_EXCEPTION = "javax.servlet.error.exception";

    private static final String STATUS_CODE = "javax.servlet.error.status_code";

    private static final String ERROR_MESSAGE = "javax.servlet.error.message";

    public static Object failFast(RequestContext context, int code, int statusCode, String message) {
        fillError(context, code, statusCode, message);
        throw new ZuulFilterException(message);
    }

    public static Object fillError(RequestContext context, int code, int statusCode, String message) {
        HttpServletRequest request = context.getRequest();
        if (Objects.nonNull(request.getAttribute(CROWD_ERROR))) {
            return null;
        }
        context.setSendZuulResponse(false);
        context.setResponseStatusCode(statusCode);
        JSONObject object = new JSONObject();
        object.put("code", code);
        object.put("message", message);
        object.put("desc", message);
        context.getResponse().setContentType("text/html;charset=UTF-8");
        context.setResponseBody(object.toJSONString());
        request.setAttribute(CROWD_ERROR, object);
        return null;

    }


    public static Integer getStatusCode(RequestAttributes requestAttributes) {
        return getAttribute(requestAttributes, STATUS_CODE);
    }

    public static void fillError(RequestContext context, Throwable throwable) {
        HttpServletRequest request = context.getRequest();
        request.setAttribute(ERROR_EXCEPTION, throwable);
        request.setAttribute(ERROR_MESSAGE, throwable.getMessage());
        request.setAttribute(STATUS_CODE, context.getResponseStatusCode());
    }

    public static Map<String, Object> getCrowdError(RequestAttributes requestAttributes) {
        return getAttribute(requestAttributes, CROWD_ERROR);
    }

    public static Throwable getErrorException(RequestAttributes requestAttributes) {
        return getAttribute(requestAttributes, ERROR_EXCEPTION);
    }

    @SuppressWarnings("unchecked")
    private static <T> T getAttribute(RequestAttributes requestAttributes, String name) {
        return (T)requestAttributes.getAttribute(name, RequestAttributes.SCOPE_REQUEST);
    }

}
